﻿Option Strict On

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient


Public Class DataSystemUser

    Public Shared Function Validate(ByVal SystemUserUsername As String, ByVal SystemUserPassword As String) As SystemUser

        Dim Command As New SqlCommand()
        Command.Connection = Data.OpenDatabase()
        Command.CommandText = "SELECT * FROM SystemUser WHERE SystemUserUsername = @SystemUserUsername AND SystemUserPassword = @SystemUserPassword;"
        Command.Parameters.AddWithValue("@SystemUserUsername", SystemUserUsername)
        Command.Parameters.AddWithValue("@SystemUserPassword", SystemUserPassword)

        Dim Table As New DataTable()
        Table.Load(Command.ExecuteReader())

        If Table.Rows.Count > 0 Then

            For Each Row As DataRow In Table.Rows

                Dim SystemUser As New SystemUser()
                SystemUser.SystemUserID = Convert.ToInt32(Row.Item("SystemUserID"))
                SystemUser.SystemUserName = Row.Item("SystemUserName").ToString()
                SystemUser.SystemUserUsername = Row.Item("SystemUserUsername").ToString()
                SystemUser.SystemUserPassword = Row.Item("SystemUserPassword").ToString()

                Return SystemUser
            Next

        End If

        Return Nothing
    End Function

    Public Shared Function InsertSystemUser(ByVal SystemUser As SystemUser) As Exception

        Try
            Dim Command As New SqlCommand()
            Command.Connection = Data.OpenDatabase()

            Command.CommandText = "SELECT COUNT(SystemUserID) AS RecordCount FROM SystemUser WHERE SystemUserUsername = @SystemUserUsername"
            Command.Parameters.Clear()
            Command.Parameters.AddWithValue("@SystemUserUsername", SystemUser.SystemUserUsername)

            Dim RecordCount As Integer = CInt(Command.ExecuteScalar())

            If RecordCount > 0 Then

                Dim E As New Exception("Username Already Exists")
                Return E

            End If

            Command.CommandText = "INSERT INTO SystemUser VALUES (@SystemUserUsername, @SystemUserPassword, @SystemUserName)"
            Command.Parameters.Clear()
            Command.Parameters.AddWithValue("@SystemUserUsername", SystemUser.SystemUserUsername)
            Command.Parameters.AddWithValue("@SystemUserPassword", SystemUser.SystemUserPassword)
            Command.Parameters.AddWithValue("@SystemUserName", SystemUser.SystemUserName)
            Command.ExecuteNonQuery()
        Catch Ex As Exception
            Return Ex
        End Try

        Return Nothing
    End Function

End Class
